import 'package:flutter/cupertino.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/ChooserBox.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:hitutor/Widget/MyInput.dart';
import 'package:hitutor/Widget/MyPage.dart';
import 'package:hitutor/Widget/Star.dart';

import 'FavoriteTeacherSearch.dart';
import 'TeacherInfo.dart';

class FavoriteTeacher extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _FavoriteTeacher();
  }
}

class _FavoriteTeacher extends State<FavoriteTeacher> {
  List<dynamic> languageList = [];
  int languageIndex = -1;

  openLanguageChooser() {
    showWheelDialog2(context, "", languageList, "languageName", (index) {
      chooseLanguage(index);
    });
  }

  chooseLanguage(int index) {
    languageIndex = index;
    getMaybeLoveTeacher();
    setState(() {});
  }

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      getLanguage();
      getFavoriteTeacher();
      getMaybeLoveTeacher();
    });
    super.initState();
  }

  getLanguage() {
    HttpGo(context).get("/Teacher/GetTeachingLanguageList", {}, (data) {
      languageList = data["languageList"];
    }, (code, error) => showToast(error));
  }

  List<dynamic> favoriteTeacherList = [];

  getFavoriteTeacher() {
    HttpGo(context).post("/Teacher/GetFavoriteTeacherList", {"studentId": Global.studentId}, (data) {
      favoriteTeacherList = data["teacherList"];
      setState(() {});
    }, (code, error) => showToast(error));
  }

  List<dynamic> maybeLoveTeacherList = [];

  getMaybeLoveTeacher() {
    String api = (languageIndex >= 0 ? "?languageCode=${languageList[languageIndex]["languageCode"]}" : "");
    HttpGo(context).get("/Teacher/GetRecommendTeacherList$api", {}, (data) {
      maybeLoveTeacherList = data["teacherList"];
      setState(() {});
    }, (code, error) => showToast(error));
  }

  @override
  Widget build(BuildContext context) {
    String language = languageIndex >= 0 ? languageList[languageIndex]["languageName"] : "";
    return MyPage(
        "最愛教師設定",
        SingleChildScrollView(
            child: Container(
                padding: EdgeInsets.all(16),
                child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                  ChooserBox(language.isEmpty ? "選擇語言" : language, onTap: openLanguageChooser),
                  Container(
                      decoration: Global.getBg(MyColor.F2, 5),
                      padding: EdgeInsets.fromLTRB(4, 0, 8, 0),
                      margin: EdgeInsets.fromLTRB(0, 8, 0, 8),
                      height: 28,
                      child: Row(children: [
                        Expanded(
                            child: NormalInput(
                                hintText: "輸入老師名字",
                                fontSize: 12,
                                onSubmit: (value) {
                                  PageUtil().open(context,
                                      FavoriteTeacherSearch(searchKey: value, languageList: languageList, languageIndex: languageIndex));
                                })),
                        LocalImage("search_blue.png", width: 16)
                      ])),
                  ListView.builder(
                      itemCount: favoriteTeacherList.length,
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      itemBuilder: (BuildContext context, int index) {
                        return ItemTeacher(teacherData: favoriteTeacherList[index]);
                      }),
                  Visibility(
                      visible: maybeLoveTeacherList.length > 0,
                      child: Container(
                          margin: EdgeInsets.fromLTRB(0, 16, 0, 8),
                          child: Text("您可能有興趣", style: TextStyle(fontSize: 16, color: MyColor.Green, fontWeight: FontWeight.bold)))),
                  ListView.builder(
                      itemCount: maybeLoveTeacherList.length,
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      itemBuilder: (BuildContext context, int index) {
                        return ItemTeacher(teacherData: maybeLoveTeacherList[index]);
                      })
                ]))));
  }
}

class ItemTeacher extends StatefulWidget {
  dynamic teacherData;

  ItemTeacher({required this.teacherData});

  @override
  State<StatefulWidget> createState() {
    return _ItemTeacher();
  }
}

class _ItemTeacher extends State<ItemTeacher> {
  switchLike() {
    HttpGo(context).post("/Teacher/SetFavoriteTeacher", {
      "studentId": Global.studentId,
      "teacherId": widget.teacherData["teacherId"],
      "stateTag": widget.teacherData["isFavoriteTeacher"] ? 0 : 1,
    }, (data) {
      widget.teacherData["isFavoriteTeacher"] = !widget.teacherData["isFavoriteTeacher"];
      setState(() {});
    }, (code, error) => showToast(error));
  }

  @override
  Widget build(BuildContext context) {
    List<dynamic> levelList = widget.teacherData["teachingLevelList"] ?? [];
    String level = levelList.join("、");
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          showWidgetDialog(context, TeacherInfo(widget.teacherData));
        },
        child: Container(
            padding: EdgeInsets.fromLTRB(0, 8, 0, 8),
            child: Row(children: [
              Container(
                  decoration: Global.getBg(MyColor.F3, 24),
                  child: NetImage(widget.teacherData["photo"], width: 40, height: 40, radius: 20)),
              Container(width: 8),
              Expanded(
                  child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                Row(children: [
                  Text("${widget.teacherData["teacherName"]}", style: TextStyle(fontWeight: FontWeight.bold)),
                  Container(width: 4),
                  Star(canChoose: false, value: widget.teacherData["teacherGrade"] + 0.0, starWidth: 18, diverWidth: 0)
                ]),
                Text("$level", style: TextStyle(color: MyColor.C99))
              ])),
              LocalImage(widget.teacherData["isFavoriteTeacher"] ? "like_on.png" : "like_off.png", width: 24, onTap: switchLike)
            ])));
  }
}
